package com.example.bishe.toolclass;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author yws
 * @Date 2022/3/11 17:40
 */
@Component
public class GitTonk {
    @Resource
    ApiReturnDate apiReturnDate;
    @Resource
    JsonValue jsonValue;
    @Resource
    RedisUtil redisUtil;

    public String gitTongXunTonk() {//获取到通信录对应功能的token
        String access_token1 = "";
        String Url1 = MyEnum.ACCESS_TOKEN.getValue() +
                "corpid=" + MyEnum.APPID.getValue() +
                "&corpsecret=" + MyEnum.TONGXUN_CORPSECRET.getValue();
        JSONObject mydate = apiReturnDate.Mydate(Url1);//获得返回的JSON数据
        access_token1 = jsonValue.getValue(mydate, "access_token");
        //System.out.println(jsonValue.getValue(mydate, "expires_in"));
        redisUtil.set("useraccess_token", access_token1, 7100);
        return "";
    }

    public String gitDongLuTonk() {//获取到登录功能的token
        String Url1 = MyEnum.ACCESS_TOKEN.getValue() +
                "corpid=" + MyEnum.APPID.getValue() +
                "&corpsecret=" + MyEnum.CORPSECRET.getValue();
        //System.out.println("你好我看到了这里了");
        JSONObject mydate = apiReturnDate.Mydate(Url1);
        //System.out.println(mydate);
        String access_token = jsonValue.getValue(mydate, "access_token");
        redisUtil.set("dengluaccess_token", access_token, 7100);
        return "access_token";
    }

    //寻找Redis中对应的token，若有则直接返回，若没有则申请
    public String AccessToken(String str) {//参数str为需要的的token类型的键，根据str找到对应的数据。
        if (redisUtil.get(str)==null) {//获取token是否已过期，如果过期则去进行生成，否则去获取
            if (str.equals("useraccess_token"))
                str = gitTongXunTonk();
            else if (str.equals("dengluaccess_token"))
                str = gitDongLuTonk();
        } else {
            str = (String) redisUtil.get(str);
        }
        return str;
    }

}

